package com.jlkf.service.impl.website;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.jlkf.common.Constant;
import com.jlkf.common.rong.models.CodeSuccessResult;
import com.jlkf.common.rong.models.TokenResult;
import com.jlkf.common.rong.util.RongCloud;
import com.jlkf.dao.AuthcodeMapper;
import com.jlkf.dao.DriverAccessoryMapper;
import com.jlkf.dao.UserBrankMapper;
import com.jlkf.dao.UserMapper;
import com.jlkf.pojo.Authcode;
import com.jlkf.pojo.DriverAccessory;
import com.jlkf.pojo.User;
import com.jlkf.pojo.UserBrank;
import com.jlkf.service.util.LanguageUtils;
import com.jlkf.service.util.RegexUtil;
import com.jlkf.service.util.StringTools;
import com.jlkf.service.website.LoginService;
import com.jlkf.view.WebsiteUserForm;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.util.DateUtil;
import com.platform.server.util.MD5Util;
import com.platform.server.util.RandomUtil;

@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private AuthcodeMapper authCodeMapper;
	@Autowired
	private UserBrankMapper userBrankMapper;
	@Autowired
	private DriverAccessoryMapper driverAccessoryMapper;

	// 乘客登录 密码与验证码
	@Override
	public ReturnData getPassengersLogin(String json) {
		User u = StringTools.json2Obj(json, User.class);
		if (u == null) {
			return new ReturnData(201, "List must be filled。");
		}
		User uu = null;
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		map.put("telephone", u.getTelephone());
		map.put("identity", u.getIdentity());// 身份 1普通用户 2司机
		map.put("isDeleted", 0);// 是否删除 0否 1是
		try {
			List<User> list = userMapper.getLogin(map);
			if (list.size() > 0) {
				if (!StringTools.isEmpty(u.getPassword())) {// 密码登录
					if (u.getPassword() != null && u.getPassword().length() > 18) {
						return new ReturnData(203, "Use between 8 – 19 characters in length");
					}
					String newPass = MD5Util.getMD5(u.getPassword());
					map.put("password", newPass);
					List<User> list1 = userMapper.getLogin(map);// 账号密码
					if (list1.size() == 0) {// 账号密码正确
						return new ReturnData(204, "Password is incorrect！");
					}
					uu = list.get(0);
					uu.setPassword(null);
					if (uu.getIsDeleted() == 2) {// 设置封号（1.未封 2.已封）
						return new ReturnData(209, "You account has been suspended.");
					}
					return new ReturnData(uu, 200, "success");
				} else {// 验证码登录
					map.put("platform", u.getIdentity());
					List<Authcode> list2 = authCodeMapper.getList(map);// 验证码
					if (u.getIdentity() == 2) {// 司机身份
						if (list.get(0).getDriverStatus() != 1) {// 司机审核状态 0待审核
																	// 1审核成功
																	// 2审核失败
							return new ReturnData(213, "Sorry, your account has not been verified successfully, you cannot log in temporarily.");
						}
					}
					if (list2.size() == 0) {// 没有验证码
						return new ReturnData(205, "Resend verification code");
					}
					String vCode = list2.get(0).getVcode();//
					if (!vCode.equals(u.getvCode())) {// 验证码不一致
						return new ReturnData(207, "Verification code error");
					}
					Date d = new Date();
					// 毫秒ms
					long diff = d.getTime() - list2.get(0).getCreateDate().getTime();
					long diffMinutes = diff / (60 * 1000) % 60;
					if (diffMinutes > 10) {
						return new ReturnData(208, "Verification code expired");
					}
					uu = list.get(0);
					uu.setPassword(null);
					if (uu.getIsDeleted() == 2) {// 设置封号（1.未封 2.已封）
						return new ReturnData(209, "You account has been suspended.");
					}
					if(u.getIdentity()==2){//司机
						map.put("uId", uu.getId());
						List<UserBrank> ublist=userBrankMapper.getUserBrank(map);
						if(ublist.size()>0){
							map1.put("userBrank", ublist.get(0));
						}
						List<DriverAccessory> dalist=driverAccessoryMapper.getUserCars(uu.getId());
						map1.put("driverAccessoryList", dalist);
						map1.put("user", uu);
						return new ReturnData(map1,200,"success");
					}
					return new ReturnData(uu, 200, "success");
				}
			} else {
				return new ReturnData(202, "Account no");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	// 忘记密码
	@Override
	public Object forgetPassword(String json) {
		User u = StringTools.json2Obj(json, User.class);
		if (u == null) {
			return new ReturnData(201, "List must be filled。");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("telephone", u.getTelephone());
		map.put("identity", 1);// 身份 1普通用户 2司机
		map.put("isDeleted", 0);// 是否删除 0否 1是
		// 设置封号（1.未封 2.已封）
		try {
			if(!u.getPassword().equals(u.getRetypePassword())){
				return new ReturnData(302,"Password does not match");
			}
			List<User> list = userMapper.getLogin(map);// 查询用户是否存在
			if (list.size() == 0) {
				return new ReturnData(202, "Account does not exist");
			}
			if (list.get(0).getIsDeleted() == 2) {// 设置封号（1.未封 2.已封）
				return new ReturnData(209, "You account has been suspended.");
			}
			if (u.getPassword() != null && (u.getPassword().length() > 18 || u.getPassword().length() < 4)) {
				return new ReturnData(203, "Use between 8 – 19 characters in length");
			}
				List<Authcode> list2 = authCodeMapper.getList(map);// 验证码
				if (list2.size() == 0) {// 无验证码
					return new ReturnData(205, "Resend verification code");
				}
				String vCode = list2.get(0).getVcode();//
				if (!vCode.equals(u.getvCode())) {// 验证码不一致
					return new ReturnData(207, "Verification code error");
				}
					Date d = new Date();
					// 毫秒ms
					long diff = d.getTime() - list2.get(0).getCreateDate().getTime();
					long diffMinutes = diff / (60 * 1000) % 60;
					if (diffMinutes >10) {
						return new ReturnData(208, "Verification code expired");
					}
						u.setId(list.get(0).getId());
						u.setPassword(MD5Util.getMD5(u.getPassword()));
						int num = userMapper.updateByPrimaryKeySelective(u);
						if (num == 0) {
							return new ReturnData(210, "Alteration Failed");
						}
						return new ReturnData(200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}

	}

	// 企业注册
	@Override
	public Object registration(String json) {
		User u = StringTools.json2Obj(json, User.class);
		if (u == null) {
			return new ReturnData(201, "List must be filled。");
		}
		try {
			Map<String, Object> map = new HashMap<>();
		String userNo=getUserNo();
			u.setUserAccount(userNo);
			u.setCreateTime(new Date());
			int num = userMapper.insertSelective(u);
			if (num == 0) {
				return new ReturnData(201, "Registration failed");
			}
			return new ReturnData(200, "Registered successfully");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}
	// 获取订单
		private String getUserNo() {
			String str = userMapper.selectMaxUserNo();
			if (str == null) {
				str = "00000" + 1;
			} else {
				Integer no = Integer.parseInt(str);
				if (no < 9) {
					str = "00000" + (no + 1);
				} else if (no >= 9 && no < 99) {
					str = "0000" + (no + 1);
				} else if (no >= 99 && no < 999) {
					str = "000" + (no + 1);
				}else if(no >= 999 && no < 9999){
					str = "00" + (no + 1);
				}else if(no >= 9999 && no < 99999){
					str = "0" + (no + 1);
				} else {
					str = "" + (no + 1);
				}
			}
			String no = "E" + str;
			return no;
		}
	// 企业登录
	@Override
	public Object getEnterpriseLogin(String json) {
		User u = StringTools.json2Obj(json, User.class);
		if (u == null) {
			return new ReturnData(201, "List must be filled。");
		}
		User uu = null;
		Map<String, Object> map = new HashMap<>();
		try {
			map.put("userAccount", u.getUserAccount());
			map.put("identity", 4);// 身份 1普通用户 2司机 3企业申请注册  4企业账号
			map.put("isDeleted", 0);// 是否删除 0否 1是
			List<User> list = userMapper.getLogin(map);
			if (list.size() == 0) {
				return new ReturnData(202, "Account does not exist");
			}
			map.put("password", u.getPassword());
			List<User> list1 = userMapper.getLogin(map);
			if (list1.size() == 0) {
				return new ReturnData(203, "Password is incorrect！");
			}
			uu = list1.get(0);
			return new ReturnData(uu, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object updateUserInfo(String json) {
		User uu = StringTools.json2Obj(json, User.class);
		if(uu==null){
			return new ReturnData(201,"List must be filled");
		}
		try {
			if(uu.getPicture()!=null){//修改了用户的头像
				User uus =userMapper.selectByPrimaryKey(uu.getId());
				RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);//融云
					CodeSuccessResult userRefreshResult = rongCloud.user.refresh(uus.getId().toString(), uus.getFirstName(), uus.getPicture());
					System.out.println("rongCloud_refresh:  " + userRefreshResult.toString());
					if(userRefreshResult.getCode()!=200){
						return new ReturnData(300,"Editing failed");
					}
			}
			int num=userMapper.updateByPrimaryKeySelective(uu);
			if(num==0){
				return new ReturnData(203,"Editing failed");
			}
			return new ReturnData(200,"Editing completed.");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	//司机注册
	@Override
	public Object driverRegistration(String json) {
		WebsiteUserForm wuf = StringTools.json2Obj(json, WebsiteUserForm.class);
		if (wuf == null) {
			return new ReturnData(201, "List must be filled。");
		}
	   boolean flag=true;int code=200;String msg="success";
		try {
			User u=wuf.getUser();
			u.setCreateTime(new Date());
			u.setIdentity(2);//身份为司机
			Map<String, Object> map = new HashMap<>();
			// 2司机 3企业
				String inviattionCode = RandomUtil.getRandomString(8);
				map.put("inviattionCode", inviattionCode);
				List<User> list4 = userMapper.getLogin(map);// inviattionCode是否已被使用
				if (list4.size() > 0) {
					u.setInviattionCode(RandomUtil.getRandomString(8));
				} else {
					u.setInviattionCode(inviattionCode);
				}
				if(!StringTools.isEmpty(u.getPassword())){
					String pass = MD5Util.getMD5(u.getPassword());
					u.setPassword(pass);
				}
				u.setPicture("http://13.55.2.125:8080//file//fab//user.jpg");
				int num=userMapper.insertSelective(u);	
				if(num==0){
					flag=false; code=202;msg="fail";
				}else{
					DriverAccessory da = wuf.getDriverAccessory();
					Map<String,Object> map1 = new HashMap<>();
					map1.put("identity", 2);
					map1.put("telephone", u.getTelephone());
					List<User> userList = userMapper.getLogin(map);
					if(userList.size()>0){
						da.setuId(userList.get(0).getId());
						if(da.getCarType().equals("3")){
							da.setOpenServerType("1,2,3");
						}else if(da.getCarType().equals("3")){
							da.setOpenServerType("1,2");
						}else{
							da.setOpenServerType("1");
						}
						int n=driverAccessoryMapper.insertSelective(da);
						if(n==0){
							flag=false;code=203;msg="fail";
						}
						map.put("identity", 2);
						map.put("telephone", u.getTelephone());
						List<User>  list2=userMapper.getLogin(map);
						RongCloud rongCloud = RongCloud.getInstance(Constant.RONG_CLOUD_appKey, Constant.RONG_CLOUD_appSecret);
						 if(list2.size()>0){
							 TokenResult userGetTokenResult = rongCloud.user.getToken(list2.get(0).getId().toString(), list2.get(0).getFirstName(), "http://13.55.2.125:8080//file//fab//user.jpg");
							 if(userGetTokenResult!=null&&userGetTokenResult.getCode()==200){
								 User uus = list2.get(0);
								 uus.setRongCloudToken(userGetTokenResult.getToken());//保存融云的token
								int nus= userMapper.updateByPrimaryKeySelective(uus);
								if(nus==0){
									code=305;msg = LanguageUtils.returnLan(2, "registration_failed");
								}
							 }else{
								 code=306;msg = LanguageUtils.returnLan(2, "registration_failed");
							 }
						 }
					}
					
					}
				if(!flag){
					TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
				}
				return new ReturnData(code,msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object getUserDetail(Long uId) {
		try {
			User user  =  userMapper.selectByPrimaryKey(uId);
			user.setPassword(null);
			return new ReturnData(user,200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	@Override
	public Object getUserbrank(Long uId) {
		Map<String,Object> map = new HashMap<>();
		map.put("uId", uId);
		try {
			List<UserBrank> ublist=userBrankMapper.getUserBrank(map);
			if(ublist.size()>0){
				return new ReturnData(ublist.get(0),200,"success");
			}
			return new ReturnData(null,202,"You have not added the bank card, please add a bank card first.");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong ");
		}
	}

	
	

}
